import 'package:dali_ng_pera/manager/dnp_plugin_manager.dart';
import 'package:dali_ng_pera/net/dnp_net_config.dart';
import 'package:dali_ng_pera/page/browser/dnp_browser_page.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:webview_flutter/webview_flutter.dart';

import '../../mob/dnp_mob.dart';
import '../../tool/dnp_time_tool.dart';
import '../certification/dnp_certification_page.dart';
import '../main/dnp_main_controller.dart';

class DnpBrowserController extends GetxController {

  BuildContext? ctx;

  double progressValue = 0;

  WebViewController browserController = WebViewController();

  String titleName = "";

  String _browserUrl = "";

  int timeStamp = 0;

  bool isWhenHalf = false;

  List<String> jsNames = [
    "BrightWith",
    "HearSlowed",
    "CurveWhite",
    "ThroughOf",
    "NetCame",
    "TheBe",
    "AndBe",
    "WhenHalf"
  ];

  @override
  void onInit() {
    super.onInit();

    _addBrowserParams();

    _addJs();
  }

  void request(String path) {
    _browserUrl = path;
    browserController.loadRequest(Uri.parse(DnpNetConfig().concatenateUrl(path)));
  }

  void _addBrowserParams() {
    browserController
      ..setBackgroundColor(Colors.transparent)
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..setNavigationDelegate(
          _navigationDelegate
      );
  }

  void _addJs() {
      for (String name in jsNames) {
        browserController.addJavaScriptChannel(name, onMessageReceived: (JavaScriptMessage message) {
          if (name == "BrightWith") {
            brightWith(message.message);
          }else if (name == "HearSlowed") {
            hearSlowed();
          }else if (name == "CurveWhite") {
            curveWhite(message.message);
          }else if (name == "ThroughOf") {
            throughOf();
          }else if (name == "NetCame") {
            netCame();
          }else if (name == "TheBe") {
            theBe(message.message);
          }else if (name == "AndBe") {
            andBe();
          }else if (name == "WhenHalf") {
            whenHalf();
          }
        });
      }
  }

  NavigationDelegate get _navigationDelegate {
    return NavigationDelegate(
      onProgress: (int progress) {
        reviseProgress(progress / 100);
      },
      onPageStarted: (String url) {
        reviseProgress(0.0);
      },
      onPageFinished: (String url) {
        reviseTitleName();
        reviseProgress(1.0);
      },
    );
  }

  void reviseProgress(double  progress) {
    progressValue = progress;
    update(["reviseProgress"]);
  }

  void reviseTitleName() async {
    String? title = await browserController.getTitle();

    if (title == null || title.isEmpty || title == "undefined") {
      title = "Dali Ng Pera";
    }
    titleName = title;
    update(["reviseTitle"]);
  }

  void brightWith(String ms) {
    String message = messageValue(ms);

    if (message.isNotEmpty) {
      Get.to(() => DnpBrowserPage(path: message));
    }
  }

  void hearSlowed() {
    if (isWhenHalf) {
      isWhenHalf = false;
    }else {
      Get.back();
    }
  }

  void curveWhite(String ms) {

    RegExp regExp = RegExp(r'\[(.*?)\]');

    Match? match = regExp.firstMatch(ms);

    if(match != null) {
      String content = match.group(1) ?? "";
      if (content.isNotEmpty && content.startsWith("ios://Dali.ngPe.ra/aisle")) {

        Uri uri = Uri.parse(content);

        // 获取查询参数
        String? alreadyValue = uri.queryParameters['already'];

        if (alreadyValue != null && alreadyValue.isNotEmpty) {
          Get.to(() => DnpCertificationPage(already: alreadyValue));
        }
      }
    }
  }

  void throughOf() {
    Get.back();
    Get.find<DnpMainController>().scrollToHomeWidget();
  }

  void netCame() {
    DnpPluginManager().plugin.showSKStore();
  }

  void theBe(String ms) {
    final t = DnpTimeTool.timestamp;
    DnpMob.inexplicable("10", t, t);
  }

  void andBe() {
    timeStamp = DnpTimeTool.timestamp;
  }

  void whenHalf() {
    isWhenHalf = true;
    Get.back();
    DnpMob.inexplicable("8", timeStamp,DnpTimeTool.timestamp);
  }

  String messageValue(String ms) {
    int startIndex = ms.indexOf("https://");
    int endIndex = ms.indexOf("]", startIndex);

    // 提取 URL
    if (startIndex != -1 && endIndex != -1) {
      String url = ms.substring(startIndex, endIndex);
      return url;
    }
    return "";
  }
}